package cn.com.lyj6851.modules.wechat;

import cn.com.lyj6851.modules.mp.domain.YdyWechatReply;
import cn.com.lyj6851.modules.mp.service.YdyWechatReplyService;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Api(tags = "商城:微信回復管理")
@RestController
@RequestMapping("api")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WechatReplyController {

    private final YdyWechatReplyService ydyWechatReplyService;



    @ApiOperation(value = "查询")
    @GetMapping(value = "/ydyWechatReply")
    @PreAuthorize("@per.check('admin','WECHATREPLY_ALL','WECHATREPLY_SELECT')")
    public ResponseEntity getYdyWechatReplys(){
        return new ResponseEntity<>(ydyWechatReplyService.isExist("subscribe"), HttpStatus.OK);
    }


    @ApiOperation(value = "新增自动回复")
    @PostMapping(value = "/ydyWechatReply")
    @PreAuthorize("@per.check('admin','WECHATREPLY_ALL','WECHATREPLY_CREATE')")
    public ResponseEntity create(@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        YdyWechatReply ydyWechatReply = new YdyWechatReply();
        YdyWechatReply isExist = ydyWechatReplyService.isExist(jsonObject.get("key").toString());
        ydyWechatReply.setKey(jsonObject.get("key").toString());
        ydyWechatReply.setStatus(Integer.valueOf(jsonObject.get("status").toString()));
        ydyWechatReply.setData(jsonObject.get("data").toString());
        ydyWechatReply.setType(jsonObject.get("type").toString());
        if(ObjectUtil.isNull(isExist)){// 如果没有自动回复消息;则创建
            ydyWechatReplyService.create(ydyWechatReply);
        }else{// 否则更新
            ydyWechatReply.setId(isExist.getId());
            ydyWechatReplyService.upDate(ydyWechatReply);
        }

        return new ResponseEntity(HttpStatus.CREATED);
    }





}
